import time
import cv2
import numpy as np
from PyQt6.QtCore import QThread, pyqtSignal

class VideoThread(QThread):
    """视频推理线程"""
    frame_signal = pyqtSignal(np.ndarray)
    results_signal = pyqtSignal(list)
    finished_signal = pyqtSignal()

    def __init__(self, model_processor, video_path):
        super().__init__()
        self.model_processor = model_processor
        self.video_path = video_path
        self.running = True

    def run(self):
        cap = cv2.VideoCapture(self.video_path)

        while self.running and cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break

            # 推理
            results = self.model_processor.process_frame(frame)
            annotated_frame = results[0].plot()  # 绘制检测结果

            # 发送处理后的帧和检测结果
            self.frame_signal.emit(annotated_frame)

            # 提取检测结果信息
            detections = self.model_processor.extract_detections(results)
            self.results_signal.emit(detections)

            # 控制帧率
            time.sleep(0.03)  # 约30fps

        cap.release()
        self.finished_signal.emit()

    def stop(self):
        self.running = False
